/*
 * Copyright (c) 2025 Industrial Software Feature Database
 */
package com.comac.ins.isfd.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.comac.ins.common.core.constant.CommonConstant;
import com.comac.ins.common.core.exception.base.BaseException;
import com.comac.ins.common.core.utils.MapstructUtils;
import com.comac.ins.common.core.utils.StringUtils;
import com.comac.ins.common.mybatis.core.page.PageQuery;
import com.comac.ins.common.mybatis.core.page.TableDataInfo;
import com.comac.ins.isfd.domain.IsfdModelManagementCalculateRefNonstandardocs;
import com.comac.ins.isfd.domain.IsfdModelManagementNonstandardocs;
import com.comac.ins.isfd.domain.bo.IsfdModelManagementNonstandardocsBo;
import com.comac.ins.isfd.domain.vo.IsfdModelManagementNonstandardocsVo;
import com.comac.ins.isfd.mapper.IsfdModelManagementCalculateRefNonstandardocsMapper;
import com.comac.ins.isfd.mapper.IsfdModelManagementNonstandardocsMapper;
import com.comac.ins.isfd.service.IIsfdModelManagementNonstandardocsService;
import com.comac.ins.system.service.ISysDictDataService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 模型组件-非标文件Service业务层处理
 *
 * @author Lion Li
 * @date 2024-09-13
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class IsfdModelManagementNonstandardocsServiceImpl implements IIsfdModelManagementNonstandardocsService {
    @Autowired
    private IsfdModelManagementNonstandardocsMapper baseMapper;

    @Autowired
    private IsfdModelManagementCalculateRefNonstandardocsMapper isfdModelManagementCalculateRefNonstandardocsMapper;

    /**
     * 查询模型组件-非标文件
     *
     * @param id 主键
     * @return 模型组件-非标文件
     */
    @Override
    public IsfdModelManagementNonstandardocsVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询模型组件-非标文件列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 模型组件-非标文件分页列表
     */
    @Override
    public TableDataInfo<IsfdModelManagementNonstandardocsVo> queryPageList(IsfdModelManagementNonstandardocsBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<IsfdModelManagementNonstandardocs> lqw = buildQueryWrapper(bo);
        Page<IsfdModelManagementNonstandardocsVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的模型组件-非标文件列表
     *
     * @param bo 查询条件
     * @return 模型组件-非标文件列表
     */
    @Override
    public List<IsfdModelManagementNonstandardocsVo> queryList(IsfdModelManagementNonstandardocsBo bo) {
        LambdaQueryWrapper<IsfdModelManagementNonstandardocs> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }
    @Autowired
    private ISysDictDataService iSysDictDataService;
    @Override
    public IsfdModelManagementNonstandardocsVo save(MultipartFile multipartFile,String remark) {

        //1.非标文件目录确定
        //通过字典获取文件前缀(/xxx/xxx/xxx/)
        String prefixPath = iSysDictDataService.selectDictValueByTypeAndLabel(CommonConstant.SYS_COMMON_DICT_TYPE,
            CommonConstant.MODEL_MANAGEMENT_NONSTANDARDOCS_PREFIX);
        if (StringUtils.isBlank(prefixPath)) {
            throw new BaseException("非标文件存储路径前缀未配置，请到字典管理中配置，并重试.");
        }

        try {
            // 2.文件操作
            String fileName = multipartFile.getOriginalFilename();
            String filePath = prefixPath + System.currentTimeMillis();
            String fileUrl = filePath + "/" + fileName;
            Path targetPath = Paths.get(fileUrl);
            File dir = targetPath.getParent().toFile();
            if (!dir.exists()) {
                dir.mkdirs();
            }
            //2.写磁盘
            //获取文件的文件全名（yyy.bdf）
            //拼接文件全路径（/xxx/xxx/xxx/yyy.bdf）
            //通过java的IO工具把file按照文件全路径写入磁盘
            Files.write(targetPath, multipartFile.getBytes());
            // 3.db操作
            //封装实体类（IsfdModelManagementNonstandardocs） new出来，赋值set
            //mybatis提供的mapper.insert（实体类）
            IsfdModelManagementNonstandardocs po = new IsfdModelManagementNonstandardocs();
            po.setFileName(fileName);
            String resultStr = String.format("%.5f", (double) multipartFile.getSize() / 1024);
            po.setFileSize(Double.parseDouble(resultStr));
            po.setRemark(remark);
            po.setCreateTime(new java.util.Date());
            po.setFileUrl(fileUrl);
            baseMapper.insert(po);
            //4.返回数据
            //封装（IsfdModelManagementNonstandardocsVo） new出来，赋值set
            IsfdModelManagementNonstandardocsVo isfdModelManagementNonstandardocsVo = new IsfdModelManagementNonstandardocsVo();
            isfdModelManagementNonstandardocsVo.setFileName(po.getFileName());
            isfdModelManagementNonstandardocsVo.setFileSize(po.getFileSize());
            isfdModelManagementNonstandardocsVo.setFileUrl(po.getFileUrl());
            isfdModelManagementNonstandardocsVo.setRemark(po.getRemark());
            isfdModelManagementNonstandardocsVo.setCreateTime(po.getCreateTime());
            isfdModelManagementNonstandardocsVo.setId(po.getId());
            return isfdModelManagementNonstandardocsVo;
        } catch (Exception e) {
            log.error("上传非标文件失败", e);
            throw new BaseException("上传保存非标文件失败");
        }
    }


    private LambdaQueryWrapper<IsfdModelManagementNonstandardocs> buildQueryWrapper(IsfdModelManagementNonstandardocsBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<IsfdModelManagementNonstandardocs> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getFileName()), IsfdModelManagementNonstandardocs::getFileName, bo.getFileName());
        lqw.eq(bo.getFileSize() != null, IsfdModelManagementNonstandardocs::getFileSize, bo.getFileSize());
        lqw.eq(StringUtils.isNotBlank(bo.getFileUrl()), IsfdModelManagementNonstandardocs::getFileUrl, bo.getFileUrl());
        return lqw;
    }

    /**
     * 新增模型组件-非标文件
     *
     * @param bo 模型组件-非标文件
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(IsfdModelManagementNonstandardocsBo bo) {
        IsfdModelManagementNonstandardocs add = MapstructUtils.convert(bo, IsfdModelManagementNonstandardocs.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改模型组件-非标文件
     *
     * @param bo 模型组件-非标文件
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(IsfdModelManagementNonstandardocsBo bo) {
        IsfdModelManagementNonstandardocs update = MapstructUtils.convert(bo, IsfdModelManagementNonstandardocs.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(IsfdModelManagementNonstandardocs entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除模型组件-非标文件信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public List<IsfdModelManagementNonstandardocsVo> queryListByCalculateId(Long calculateId) {
        List<IsfdModelManagementCalculateRefNonstandardocs> isfdModelManagementCalculateRefNonstandardocs = isfdModelManagementCalculateRefNonstandardocsMapper
            .selectList(new LambdaQueryWrapper<IsfdModelManagementCalculateRefNonstandardocs>()
                .eq(IsfdModelManagementCalculateRefNonstandardocs::getCalculateId, calculateId));
        if (CollectionUtils.isEmpty(isfdModelManagementCalculateRefNonstandardocs)) {
            return new ArrayList<>();
        }
        List<Long> nonstandardocsId = isfdModelManagementCalculateRefNonstandardocs.stream().map(IsfdModelManagementCalculateRefNonstandardocs::getNonstandardocsId).toList();
        return baseMapper.selectVoBatchIds(nonstandardocsId);
    }

    @Override
    public List<IsfdModelManagementNonstandardocsVo> queryByBatchIds(List<Long> nonstandardIds) {
        return baseMapper.selectVoBatchIds(nonstandardIds);
    }
}
